// app.js

App({
  globalData: {
    baseUrl: 'http://172.28.0.15:8086/cspff/api',
    userInfo: {}, //用户信息
    userLogin: {},
    ossToken: {},
    ossUrl: '' //上传图片路径
  },
  onLaunch: function () {
    this.getUserInfo();
    this.getToken()
  },
  getUserInfo: function () {
    const that = this
    const {
      baseUrl
    } = this.globalData
    wx.login({
      success: resl => {
        console.log("login", resl);
        const code = resl.code
        const that = this
        wx.getUserInfo({
          success: res => {
            console.log("res", res);
            that.globalData.userInfo = res.userInfo
            const {
              encryptedData,
              iv
            } = res
            wx.request({
              url: baseUrl + '/auth/login', //正式服务器
              header: {
                'content-type': 'application/json'
              },
              data: {
                code: code,
                encryptedData: encryptedData,
                ivStr: iv
              },
              success: function (resa) {
                const {
                  data
                } = resa.data
                that.globalData.userLogin = data
                console.log('登录', data);
                wx.setStorageSync("wechatUser", data.wechatUser)
                // data.newUser 为true的是新用户
                if (!data.newUser) {
                  // 缓存token
                  wx.setStorageSync("token", resa.header.token)
                  // return wx.navigateTo({
                  //   url: '/pages/person/registered/index',
                  // })
                } else {
                  try {
                    wx.removeStorageSync('token')
                  } catch (e) {
                    // Do something when catch error
                  }
                }
              }
            })
          }
        })
      },
    })
  },
  getToken: function () {
    const that = this
    const {
      baseUrl
    } = this.globalData
    const nowTime = (Date.now() + '').substring(0, 11);
    const numNOWtime = Number(nowTime) + (1000 * 60 * 2)
    const numExpire = Number(that.globalData.ossToken.expire)
    console.log('nowTime', nowTime);
    if (!numExpire || numNOWtime > numExpire) {
      wx.request({
        url: baseUrl + '/oss/getToken',
        success: (res => {
          console.log("oss", res);
          const ossToken = JSON.parse(res.data.token)
          that.globalData.ossToken = ossToken
        })
      })
    } else {
      return
    }
  }
})